package com.wanghua.spring.test.xml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;

/**
 * XML 与 Java 类映射（JAXB）。
 * //JAXB 提供复杂的映射标注，比如：@XmlElement、@XmlAttribute、@XmlNs、@XmlEnum 等。
 */
public class JAXBDemo {
    public static void main(String[] args) {
        JAXBContext context;
        try {
            ArticleData articles = new ArticleData();

            Article article1 = new Article();
            article1.setAuthor("张三");
            article1.setDate("2008-12-12");
            article1.setEmail("387634@qq.com");
            article1.setTitle("XML基础");
            article1.setCategory("XML");

            Article article2 = new Article();
            article2.setAuthor("李四");
            article2.setDate("2008-12-12");
            article2.setEmail("387634@qq.com");
            article2.setTitle("Java基础");
            article2.setCategory("JAVA");

            articles.getArticles().add(article1);
            articles.getArticles().add(article2);

            context = JAXBContext.newInstance(ArticleData.class);  //创建上下文
            Marshaller marshaller = context.createMarshaller(); //java 转 XML
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");  //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  //是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);  //是否省略xml头信息（<?xml version="1.0" encoding="utf-8" standalone="yes"?>）
            marshaller.marshal(articles, new File("D:/article.xml"));  //将 java 对象转化到 XML

            Unmarshaller unmarshaller = context.createUnmarshaller(); //XML 转 java
            articles = (ArticleData) unmarshaller.unmarshal(new File("D:/article.xml"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
